package com.g.jnitext;

import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 扫描
 * scanning
 */
public class ScanConnect {
    // TODO: 2018/4/9 0009
    private Handler handler;

    public static ScanConnect scanConnect;
    private static final String SCANCONTEXT = "com.android.scancontext";
    private SerialPortModel comSerialport;
    public InputStream is;
    private OutputStream os;
    private Open open;// = new Open(false);
    private boolean isScan = true;
    private byte[] responseData = new byte[1025];
    private Context context;
    private static boolean isStopScan = true;
    private static Boolean isNew7s =false;
    private Ringtone r;
    public static int MSG_WHAT = 11;

    public ScanConnect(Context context, boolean isnew, Handler handler, int m_WHAT) {
        this.context = context;
        isNew7s = isnew;
        MSG_WHAT=m_WHAT;
        // TODO: 2018/4/9 0009
        this.handler=handler;

        if (isNew7s)
        {
            open = new Open(isNew7s);
            open.openScan();
//             TODO: 2018/4/9 0009 hy
//            if (ComNew7s.getSerialPortModel(context)!=null)
//            {
//                comSerialport = ComNew7s.getSerialPortModel(context);
//                        is = ComNew7s.is;
//                            os = ComNew7s.os;
//            }
            try {
                comSerialport = new SerialPortModel(new File("/dev/ttyHSL1"), 115200, 8, "None", 1, "None");
                is=comSerialport.getInputStream();
                os=comSerialport.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        else
        {
            open = new Open(isNew7s);
            open.openScan();
            test();
        }
        // test();
        Uri notification = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.wet);
        r = RingtoneManager.getRingtone(context, notification);
    }
//
//    public static void init(Context context,boolean isnew) {
//        isNew7s = isnew;
//        if (isNew7s)
//        {
//            ComNew7s.init(context);
//        }
//        if (scanConnect == null) {
//            synchronized (ScanConnect.class) {
//                if (scanConnect == null) {
//                    scanConnect = new ScanConnect(context);
//                }
//            }
//        }
//
//    }
//
//    private ScanConnect(Context context) {
//        this.context = context;
//
//        if (isNew7s)
//        {
//            open = ComNew7s.open;
//            open.openScan();
//            if (ComNew7s.getSerialPortModel(context)!=null)
//            {
//
//                comSerialport = ComNew7s.getSerialPortModel(context);
//                is = ComNew7s.is;
//                os = ComNew7s.os;
//
//            }
//
//
//        }
//        else
//        {
//            open = new Open(isNew7s);
//            open.openScan();
//            test();
//        }


      //  this.handler = handler;
        //TODO 这里有修改
    //    open.openScan();
//        Uri notification = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.wet);
//        r = RingtoneManager.getRingtone(context, notification);
//    }

    /**
     * 播放扫描声音
     *
     * Play scanning
     */
    private void song() {
        if (r.isPlaying()) {
            r.stop();
        }
        r.play();
    }

    /**
     * 暂停扫描
     * <p>
     * Stop the scan
     */
    public static void stopScan() {
        isStopScan = false;
    }

    /**
     * 恢复扫描
     * <p>
     * Start the scan
     */
    public static void startScan() {
        isStopScan = true;
    }

    /**
     * 打开扫描串口.
     * <p>
     * Open the scan serial port
     */
    private void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    comSerialport = new SerialPortModel(new File("/dev/ttyHSL2"), 9600, 8, "None", 1, "None");
                   // comSerialport = new SerialPortModel(new File("/dev/ttyHSL2"), 9600, 8, "None", 1, "None");
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
                is = comSerialport.getInputStream();
                os = comSerialport.getOutputStream();
            }
        }).start();
    }

    public static void receive(int keyCode) {
        if (keyCode == 223 || keyCode == 224 || keyCode == 260 || keyCode == 261) {

            scanConnect.scan();
        }
    }

    /**
     * 扫描条码并通过广播返回数据
     * <p>
     * Scan the barcode and through the boardcast return data
     */
    public void scan() {
        if (isNew7s) {
//            open.openScan();
            // TODO: 2018/4/9 0009
//            if (comSerialport == null) {
//                comSerialport = ComNew7s.getSerialPortModel(context);
//                is = ComNew7s.is;
//                os = ComNew7s.os;
//            }

        }
        new Thread(new Runnable() {
            @Override
            public void run() {
//                if (isStopScan) {
                    if (isScan) {
                        isScan = false;
                        readscanpdata();
                    }
//                }
            }
        }).start();
    }

    /**
     * 读取扫描到的条码
     * <p>
     * Read the barcode scanning
     */
    private void readscanpdata() {
        String code = "";
        int readcount;
        Arrays.fill(responseData, (byte) 0);
        FlushUartBuffer();

        open.startScan();
        readcount = read();
        if (readcount > 0) {
            code = new String(responseData, 0, readcount);
        }
        if (!TextUtils.isEmpty(code)) {
            code = replaceBlank(code);
            song();
            // TODO: 2018/4/9 0009
            Message msg = new Message();
            msg.what = MSG_WHAT;//11;
            msg.obj = code;
            handler.sendMessage(msg);

//            Intent intent = new Intent();
//            intent.putExtra("Scan_context", code);
//            intent.setAction(SCANCONTEXT);
//            context.sendBroadcast(intent);
        }
        isScan = true;
        open.stopScan();
    }

    private void FlushUartBuffer() {
        byte[] buffer_tmp = new byte[1024];
        try {
            is.read(buffer_tmp);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    private int read() {
        int available = 0;
        int index = 0;
        try {
            while (index < 11) {
                Thread.sleep(100);
                available = is.available();
                if (available > 0)
                    break;
                index++;
            }
            if (available > 0) {
                available = is.read(responseData);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return available;
    }

    /**
     * 去除条码中的换行符
     * <p>
     * Remove the newline character in the barcode
     */
    private String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 退出关闭IO流和串口
     * <p>
     * Exit close IO streams and serial port
     */
    public void close() {
        try {
            open.closeScan();
            if (comSerialport != null) {
                is.close();
                os.close();
                comSerialport.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
